package IDbConnections;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;


public class TargetDatabase {
	
	static String userid="V2THO5_1011_3B_TEAM2", password = "V2THO5_1011_3B_TEAM2";
	static String url = "jdbc:oracle:thin:@145.89.21.30:8521:cursus01";
	static Statement stmt;
	static PreparedStatement pstmt;
	static Connection con;

	
	
    public TargetDatabase() {}
    
	public static Connection getConnection()
	{		
		try {
			Class.forName("oracle.jdbc.OracleDriver");
			} 
		catch(java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
		}

		try {
			con = DriverManager.getConnection(url, userid, password);
		} 
		catch(SQLException ex) {
			System.err.println("SQLException: " + ex.getMessage());
		}
		
		return con;
	}
    
    public void applyBusinessRules (String genSQL) throws SQLException {
    	
    	try {
    		Connection con = getConnection();
    		con.setAutoCommit(false);
    	    String sql = genSQL;
    	    
    	    System.out.println("Executing SQL: " + sql);
    	    stmt = con.createStatement();
    	    stmt.executeQuery(sql);
    	    con.commit();
    	    
    	  } catch (SQLException e ) {
    		  //System.err.println("SQLException: " + e.getMessage());
    	    if (!con.isClosed()) {
    	      try {
    	        System.err.print("Transaction is being rolled back\n");
    	        con.rollback();
    	      } catch(SQLException excep) {
    	    	System.err.println("SQLException: " + excep.getMessage());
    	      }
    	    }
    	    throw e;
    	  } finally {
    	      con.setAutoCommit(true);
    		  if (!con.isClosed()) { stmt.close(); }
    		  if (!con.isClosed()) { con.close(); }
    	  }
    }
}
